package com.ruoyi.project.system.goodsclass.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.domain.Ztree;
import com.ruoyi.framework.web.domain.ZtreeStr;
import com.ruoyi.project.system.file.domain.UploadFile;
import com.ruoyi.project.system.file.service.IUploadFileService;
import com.ruoyi.project.system.goodsclass.domain.GoodsClass;
import com.ruoyi.project.system.goodsclass.dto.GoodsClassDto;
import com.ruoyi.project.system.goodsclass.enums.ClassIsHome;
import com.ruoyi.project.system.goodsclass.service.IGoodsClassService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.role.domain.Role;

/**
 * 商品类型Controller
 * 
 * @author f_baisi
 * @date 2020-06-06
 */
@Controller
@RequestMapping("/system/goodsclass")
public class GoodsClassController extends BaseController
{
    private String prefix = "system/goodsclass";

    @Autowired
    private IGoodsClassService goodsClassService;
    @Autowired
    private IUploadFileService uploadFileService;

    @RequiresPermissions("system:goodsclass:view")
    @GetMapping()
    public String goodsclass()
    {
        return prefix + "/goodsclass";
    }

    /**
     * 查询商品类型列表
     */
    @RequiresPermissions("system:goodsclass:list")
    @PostMapping("/list")
    @ResponseBody
    public List<GoodsClass> list(GoodsClass goodsClass)
    {
        List<GoodsClass> list = goodsClassService.selectGoodsClassList(goodsClass);
        return list;
    }

    /**
     * 导出商品类型列表
     */
    @RequiresPermissions("system:goodsclass:export")
    @Log(title = "商品类型", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(GoodsClass goodsClass)
    {
        List<GoodsClass> list = goodsClassService.selectGoodsClassList(goodsClass);
        ExcelUtil<GoodsClass> util = new ExcelUtil<GoodsClass>(GoodsClass.class);
        return util.exportExcel(list, "goodsclass");
    }

    /**
     * 新增商品类型
     */
    @GetMapping("/add/{parentId}")
    public String add(@PathVariable String parentId,ModelMap mmap)
    {
        GoodsClass goodsClass = null;
        if (!parentId.equals("1"))
        {
            goodsClass = goodsClassService.selectGoodsClassById(parentId);
        }
        else
        {
            goodsClass = new GoodsClass();
            goodsClass.setId("1");
            goodsClass.setName("主目录");
        }
        mmap.put("goodsClass", goodsClass);
        return prefix + "/add";
    }

    /**
     * 新增保存商品类型
     */
    @RequiresPermissions("system:goodsclass:add")
    @Log(title = "商品类型", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(GoodsClass goodsClass)
    {
        if(goodsClass.getParentId().equals("1")){
            goodsClass.setParentId(null);
            goodsClass.setIsHome(ClassIsHome.NO_NORMAL.getValue());
        }
        goodsClassService.insertGoodsClass(goodsClass);
        //通过图片路径修改附件表中的相关资源数据
//        this.uploadFileService.updateUploadFileByRealPaths(Arrays.asList(goodsClass.getHeaderRealPath(),goodsClass.getIconRealPath(),goodsClass.getLogoRealPath()),new UploadFile(null,null,null,goodsClass.getId()));
        return AjaxResult.success();
    }

    /**
     * 修改商品类型
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        GoodsClassDto goodsClass = goodsClassService.selectGoodsDtoClassById(id);
        mmap.put("goodsClass", goodsClass);
        return prefix + "/edit";
    }

    /**
     * 修改保存商品类型
     */
    @RequiresPermissions("system:goodsclass:edit")
    @Log(title = "商品类型", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(GoodsClass goodsClass)
    {
        //查询数据库获取旧数据
        GoodsClass oldClass = this.goodsClassService.selectGoodsClassById(goodsClass.getId());
        //判断数据是否存在
        if(oldClass==null){
            return AjaxResult.error("数据不存在");
        }
        //更新数据
        goodsClassService.updateGoodsClass(goodsClass);
//
//        //删除的file集合
//        List delRealPaths = new ArrayList<String>();
//
//        //新增的file集合
//        List addRealPaths = new ArrayList<String>();
//
//        //判断1.是否是新增图片 2.是否修改背景图片
//        if(oldClass.getHeader()==null){
//            addRealPaths.add(goodsClass.getHeader());
//        }else if(!oldClass.getHeader().equals(goodsClass.getHeader())){
//            //删除原本存在的旧图
//            FileUploadUtils.delete(oldClass.getHeaderRealPath());
//
//            delRealPaths.add(oldClass.getHeaderRealPath());
//
//            addRealPaths.add(goodsClass.getHeaderRealPath());
//        }
//        //判断1.是否是新增图片 2.是否修改背景图片
//        if(oldClass.getLogo()==null){
//            addRealPaths.add(goodsClass.getLogoRealPath());
//        }else if(!oldClass.getLogo().equals(goodsClass.getLogo())){
//            //删除原本存在的旧图
//            FileUploadUtils.delete(oldClass.getLogoRealPath());
//
//            delRealPaths.add(oldClass.getLogoRealPath());
//
//            addRealPaths.add(goodsClass.getLogoRealPath());
//        }
//        //判断1.是否是新增图片 2.是否修改背景图片
//        if(oldClass.getIcon()==null){
//            addRealPaths.add(goodsClass.getIcon());
//        }else if(!oldClass.getIcon().equals(goodsClass.getIcon())){
//            //删除原本存在的旧图
//            FileUploadUtils.delete(oldClass.getIconRealPath());
//
//            delRealPaths.add(oldClass.getIconRealPath());
//
//            addRealPaths.add(goodsClass.getIconRealPath());
//        }
//
//        if(delRealPaths.size()!=0){
//            //通过图片路径删除附件表中的数据
//            this.uploadFileService.deleteUploadFileByRealPaths(delRealPaths);
//        }
//        if(addRealPaths.size()!=0){
//            //通过图片路径修改附件表中的相关资源数据
//            this.uploadFileService.updateUploadFileByRealPaths(addRealPaths,new UploadFile(null,null,null,goodsClass.getId()));
//        }

        return AjaxResult.success();
    }

    /**
     * 删除商品类型
     */
    @RequiresPermissions("system:goodsclass:remove")
    @Log(title = "商品类型", businessType = BusinessType.DELETE)
    @GetMapping( "/remove/{ids}")
    @ResponseBody
    public AjaxResult remove(@PathVariable String ids)
    {
        //todo: 判断该类型下是否有商品 有的话 不允许删除

        //判断该分类下是否存在下级分类 如果存在 则不允许删除
        if(this.goodsClassService.findGoodsClassByParentIds(ids).size()!=0){
            return AjaxResult.error("该分类存在子分类,不允许删除");
        }


        //查询数据库中的旧数据
        List<GoodsClass> goodsClasses = this.goodsClassService.selectGoodsClassByIds(ids);
        //删除数据
        goodsClassService.deleteGoodsClassByIds(ids);
//        for(GoodsClass goodsClass:goodsClasses){
//            //删除原本的旧图
//            FileUploadUtils.delete(goodsClass.getIconRealPath());
//            FileUploadUtils.delete(goodsClass.getLogoRealPath());
//            FileUploadUtils.delete(goodsClass.getHeaderRealPath());
//            //删除资源文件表中的数据
//            this.uploadFileService.deleteUploadFileByRealPaths(Arrays.asList(goodsClass.getLogoRealPath(),goodsClass.getLogo(),goodsClass.getHeaderRealPath()));
//        }

        return AjaxResult.success();
    }

    /**
     * 加载所有菜单列表树
     */
    @GetMapping("/goodsclassTreeData/{all}")
    @ResponseBody
    public List<ZtreeStr> menuTreeData(Role role,@PathVariable String all)
    {
        List<ZtreeStr> ztrees = this.goodsClassService.goodsclassTreeData(all);
        return ztrees;
    }

    /**
     * 选择菜单树
     * @param classId
     * @param map
     * @return
     */
    @GetMapping("selectGoodsClassTree/{tempprefix}/{classId}/{all}")
    public String selectMenuTree(@PathVariable String classId,@PathVariable String tempprefix,
                                 @PathVariable String all,
                                 ModelMap map){
        //返回默认选择的
        if(classId.equals("1")){
            List<GoodsClass> goodsClasses = this.goodsClassService.findAll(all);
            map.put("goodsclass",goodsClasses.size()!=0?goodsClasses.get(0):null);
        }else{
            GoodsClass goodsClass = this.goodsClassService.selectGoodsClassById(classId);
            if(goodsClass==null){
                map.put("goodsclass",this.goodsClassService.findAll(all).get(0));
            }else{
                map.put("goodsclass",goodsClass);
            }
        }
        return StringUtils.replace(tempprefix,"-","/") +"/tree";
    }
}
